import React, { Component } from 'react';
import { Button, Modal, Form, Drawer, Alert, Divider, Icon, Badge } from 'antd';
import '@/assets/css/settings';
import * as CheckManagementService from '../../../axios/CheckManagement'
import * as APIServiceYQ from '../../../axios/api_yq'
import * as APIService from '../../../axios/api'
import * as APIServicePX from '../../../axios/api_px'
import { BasicLayout, BasicLayoutSearch } from '../../../components/BasicLayout';
import { BasicPagination, isInvalidObject, TableCustomize, openSuccessModal, openModalMessage, compareDate, compareString } from '../../../components/TableCustomize'
import { withPermission } from '../../../components/withpermission';
import SearchForm from './SearchForm';
// 水印
import WaterMark from '../../../components/WaterMark'

import { withRouter } from 'react-router';
const CreateButton = withPermission(Button, 'create')

class DrawingRetrieval extends Component {
  state = {
    dataSource: [],
    advanced: false,
    searchItem: {},
    pageSize: 10,
    pageNum: 1,
    total: 0,
    columns: [
      {
        title: '序号',
        dataIndex: 'dataIndex',
        width: 100,
        render: (text, record, index) => <span>{(this.state.pageNum - 1) * (this.state.pageSize) + index + 1}</span>
      },
      {
        title: '物料编码',
        dataIndex: 'partCode',
        width: 100,
        sorter: (a, b) => compareString(a.partCode, b.partCode)
      },

      {
        title: '图号',
        width: 100,
        dataIndex: 'paperCode',
        sorter: (a, b) => compareString(a.paperCode, b.paperCode),
        // editable: true
      },
      {
        title: '物料名称',
        width: 100,
        // allowEllipsis: true,
        dataIndex: 'partName',
        sorter: (a, b) => compareString(a.partName, b.partName)
      },
      {
        title: '物料规格',
        width: 100,
        // allowEllipsis: true,
        dataIndex: 'partSpec',
        sorter: (a, b) => compareString(a.partSpec, b.partSpec)
      },
      {
        title: '数量',
        width: 100,
        // allowEllipsis: true,
        dataIndex: 'partNeedNum',
        sorter: (a, b) => compareString(a.partNeedNum, b.partNeedNum)
      },
      {
        title: '仓库',
        width: 100,
        // allowEllipsis: true,
        dataIndex: 'storeName',
        sorter: (a, b) => compareString(a.storeName, b.storeName)
      },
      {
        title: '装配组别代码',
        width: 100,
        dataIndex: 'groupCode',
        sorter: (a, b) => compareString(a.groupCode, b.groupCode),
      },
      {
        title: '装配组别名称',
        width: 150,
        dataIndex: 'assemblyGroup',
        sorter: (a, b) => compareDate(a.assemblyGroup, b.assemblyGroup)
      },
      {
        title: '操作',
        width: 150,
        dataIndex: 'opts',
        render: (text, record) => <>
          <a onClick={() => this.shuiyin(record)}>查看图纸</a>
        </>
      }
    ],
    shuiyin_visiable: false,
    showTable: false,
    assemblyGroupList: [],  // 装配组别
  };
  componentDidMount() {
    // console.log(this.props.location.data)
    if (this.props.location.data) {
      this.setState({ searchItem: this.props.location.data }, this.fetch)
    } else {
      this.setState({ showTable: false })
    }
    this.getAssemblyGroup()  // 装配组别

  }
  componentWillUnmount() {
    this.setState = () => {
      return;
    };
  }
  getAssemblyGroup = () => {
    APIServicePX.queryAssemblyGroup().then(res => {
      if (res.data.code !== 200) {
        openModalMessage('warning', res.data.msg);
        return;
      }
      let assemblyGroupList = res.data.data
      this.setState({ assemblyGroupList });
    }).catch(err => {
      openModalMessage('error', err.message);
    })
  }
  //初始化加载数据
  fetch = (pageNum = 1, pageSize = 100) => {
    this.setState({ loading: true })
    const { searchItem } = this.state
    searchItem.pageNum = pageNum
    searchItem.pageSize = pageSize

    CheckManagementService.findCheckAssignAll(searchItem).then(res => {
      this.setState({ loading: false })
      if (res.data.data.code !== 200) {
        openModalMessage('warning', res.data.data.msg)
        return
      }
      this.setState({ dataSource: res.data.data.data, total: res.data.data.total, pageNum, pageSize, showTable: true })
    }).catch(err => {
      openModalMessage('error', err.message)
    })
  }

  // 水印测试
  shuiyin = () => {
    this.setState({ shuiyin_visiable: true })
  }

  handleSearch = () => {
    this.formSearch.validateFields((err, value) => {
      if (err) return;
      console.log(value)
      const { assemblyGroupList } = this.state
      let obj = assemblyGroupList.find(e => e.groupCode == value.assemblyGroup)
      value.assemblyGroup = obj?.assemblyGroup

      if (value.assembleStartDate && value.assembleStartDate.length === 2) {
        value.firstOutputDateMin = value.assembleStartDate[0].format('YYYY-MM-DD 00:00:00')
        value.firstOutputDateMax = value.assembleStartDate[1].format('YYYY-MM-DD 23:59:59')
        delete (value.assembleStartDate)
      }
      if (value.firstDeliveryDate && value.firstDeliveryDate.length === 2) {
        value.firstDeliveryDateMin = value.firstDeliveryDate[0].format('YYYY-MM-DD 00:00:00')
        value.firstDeliveryDateMax = value.firstDeliveryDate[1].format('YYYY-MM-DD 23:59:59')
        delete (value.firstDeliveryDate)
      }
      this.setState({ searchItem: value }, this.fetch);
    })
  };

  onHandleAdvanced = () => {
    this.setState({ advanced: !this.state.advanced })
  }
  // 打开详情页
  openDetails = (record) => {
    const { searchItem } = this.state;
    const data = {}
    data.batchNo = [record.batchNo]
    data.model = record.model
    localStorage.setItem('DrawingRetrieval_searchItem', JSON.stringify(searchItem));
    localStorage.setItem('DrawingRetrieval_detailsList', JSON.stringify(data));
    this.props.history.push({ pathname: "/DrawingRetrieval_Details", data: { record: data, searchItem } })
  }
  resetForm = () => {
    this.formSearch && this.formSearch.resetFields();
    this.setState({ searchItem: {}, showTable: false });
  }
  render() {
    const { loading, dataSource, showTable, advanced, columns, pageNum, pageSize, total, searchItem, assemblyGroupList } = this.state;

    const userData = JSON.parse(localStorage.getItem("userData"))
    return (
      <div>
        <BasicLayoutSearch>
          <SearchForm onSearch={this.handleSearch}
            onClick={this.onHandleAdvanced}
            advanced={advanced}
            searchItem={searchItem}
            resetForm={this.resetForm}
            assemblyGroupList={assemblyGroupList}
            ref={node => (this.formSearch = node)}
          />
        </BasicLayoutSearch>
        {
          showTable ?
            <BasicLayout buttons={
              []} name={searchItem?.batchNo} icon="table">
              {/* <Alert message={<div>已选择<span style={{ color: '#fd1818', margin: '0 3px' }}>{selectedRowKeys.length}</span>项</div>} type="info" showIcon style={{ marginBottom: 15 }} /> */}
              <TableCustomize
                columns={columns}
                rowKey={(record) => record.batchNo}
                dataSource={dataSource}
                allowRowEdit={true}
                allowDrafting={true}
                pagination={false}
                loading={loading}
              />
              <BasicPagination pageNum={pageNum} pageSize={pageSize} total={total} loadData={this.fetch} />
            </BasicLayout>
            : null
        }


        <Modal
          title='查看图纸'
          visible={this.state.shuiyin_visiable}
          width={'50%'}
          bodyStyle={{ height: '60vh' }}
          footer={null}
          onCancel={() => this.setState({ shuiyin_visiable: false })}
        >
          <WaterMark
            children={
              // <img
              //   style={{ position: 'absolute' }}
              //   // src='https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwx4.sinaimg.cn%2Fmw690%2F006f0ITUgy1gz2ecmw74aj30qw0pxq4n.jpg&refer=http%3A%2F%2Fwx4.sinaimg.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1650003584&t=0a13db0886e72ff573b27f1ad66ac20e'
              //   // src='http://192.168.31.223:8301/upload/mes/lwmes/default/2-1647919029.jpg'
              //   src='http://192.168.31.223:8301/upload/mes/lwmes/default/Chrome-1647919106.pdf'
              //   height={'100%'} width={'100%'} />
              <iframe
                style={{ position: 'absolute' }}
                src='http://192.168.31.223:8301/upload/mes/lwmes/default/Chrome-1647919106.pdf'
                height={'100%'} width={'100%'}></iframe>
            }
            options={{ content: userData.name + '_' + userData?.roleList[0]?.name }}
            style={{ height: '50vh', width: '100%' }}
          ></WaterMark>
        </Modal>
      </div>
    );
  }
}
export default Form.create()(withRouter(DrawingRetrieval));